package com.example.activiti.controller;

import com.example.activiti.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.activiti.api.process.model.ProcessDefinition;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.bpmn.model.DataGrid;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/act")
public class ActivitiController {

    //定义流程定义相关操作
    @Autowired
    private ProcessRuntime processRuntime;

    //任务相关操作的类
    @Autowired
    private TaskRuntime taskRuntime;
//
    @Autowired
    private SecurityUtil securityUtil;


    private Logger logger = LoggerFactory.getLogger(ActivitiController.class);

    @GetMapping("/findProcess")
    public String findProcess(){
        String list="";
        securityUtil.logInAs("jack");
        //分页查询出流程定义信息
        Page<ProcessDefinition> definitionPage = processRuntime.processDefinitions(Pageable.of(0,10));


        logger.info("可用流程定义总数：{}"+definitionPage.getTotalItems());
        for (ProcessDefinition processDefinition : definitionPage.getContent()){
            System.out.println("===========================");
            logger.info("流程定义内容：{}"+processDefinition);
            list+=processDefinition.toString();
            System.out.println("===========================");

        }
        return list;
    }

    @GetMapping("/startProcess")
    public void startProcess(){
//        设置登录用户
        securityUtil.logInAs("system");
        ProcessInstance processInstance = processRuntime.
                start(ProcessPayloadBuilder.
                        start().
                        withProcessDefinitionKey("demo")
                        .build());
        logger.info("流程实例的内容：{}",processInstance);
    }

    @GetMapping("/doTask")
    public void doTask(){
//        设置登录用户
        securityUtil.logInAs("jerry");
//        查询任务
        Page<Task> taskPage = taskRuntime.tasks(Pageable.of(0,10));
        if(taskPage != null && taskPage.getTotalItems()>0){
            for(Task task : taskPage.getContent()) {
//            拾取任务
                taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
                logger.info("任务内容，{}",task);
//            完成任务
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());

            }
        }

    }


}
